import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { indexOf } from 'lodash';

import { generateScoreTable } from './components/ScoreTable';
import { generateChouqianTable } from './components/ChouqianTable';
import { convertProjectCode } from './components/toolkit';
import { generateTreeTable } from './components/ScoreTree';
import { tableChangePagination } from './components/Pagination';
import { drop, endsWith } from 'lodash';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Tabs,
  Select,
  Button,
  Modal,
  message,
  Table,
  TimePicker,
  Upload,
  notification,
  Alert,
  Icon,
} from 'antd';
const TabPane = Tabs.TabPane;

import styles from './TableList.less';
import { fullDataDeal, middleDataDeal } from './components/treeData';
import { throws } from 'assert';

const FormItem = Form.Item;
const { Option } = Select;

const CreateForm = Form.create()(props => {
  const { modalVisible, form, handleAdd, handleModalVisible, curScore } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      handleAdd(fieldsValue);
    });
  };

  const format = 'HH:mm';

  return (
    <Modal
      title="修改成绩"
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => {
        form.resetFields();
        handleModalVisible();
      }}
    >
      {form.getFieldDecorator('id', {
        rules: [{ required: true, message: '请输入比赛成绩' }],
        initialValue: curScore && curScore.id,
      })(<Input type="hidden" />)}
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={curScore && curScore.team1}>
        {form.getFieldDecorator('score1', {
          rules: [{ required: true, message: '请输入得分' }],
          initialValue: curScore && curScore.score1,
        })(<Input placeholder="请输入得分" />)}
      </FormItem>

      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={curScore && curScore.team2}>
        {form.getFieldDecorator('score2', {
          rules: [{ required: true, message: '请输入得分' }],
          initialValue: curScore && curScore.score2,
        })(<Input placeholder="请输入得分" />)}
      </FormItem>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="开始时间">
        {form.getFieldDecorator('startTime', {
          initialValue: curScore && curScore.startTime && moment(curScore.startTime, format),
        })(<TimePicker format={format} />)}
      </FormItem>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="结束时间">
        {form.getFieldDecorator('endTime', {
          initialValue: curScore && curScore.endTime && moment(curScore.endTime, format),
        })(<TimePicker format={format} />)}
      </FormItem>
    </Modal>
  );
});

@connect(({ zubie, score, loading }) => ({
  zubie,
  score,
  loading: loading.models.zubie,
}))
@Form.create()
export default class SignTable extends PureComponent {
  state = {
    modalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    courts: 4,
  };

  componentDidMount() {
    const { dispatch, location } = this.props;
    const pathArray = location.pathname.split('/');
    const id = pathArray[3];
    this.setState({
      id,
    });

    dispatch({
      type: 'zubie/clean',
      payload: {},
    });

    dispatch({
      type: 'gameList/findById',
      payload: id,
      callback: () => {
        dispatch({
          type: 'zubie/queryAllZubieForGame',
          callback: () => {
            const {
              zubie: { curZubie, zubieList },
            } = this.props;
            //console.log(curZubie)
            if (!curZubie) {
              return;
            }
            const zubieMap = zubieList.map(value => {
              return value.code;
            });
            if (indexOf(zubieMap, curZubie) > -1) {
              this.onSelectZubie(curZubie);
            } else {
              this.props.dispatch({
                type: 'zubie/changeState',
                payload: {
                  curZubie: null,
                  curZubieObj: {},
                },
              });
            }
          },
        });
      },
    });

    //this.renderTree()
  }

  modifyScore = value => {
    this.setState({
      curScore: value,
    });
    this.handleModalVisible(true);
  };

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  handleAdd = fields => {
    const format = 'HH:mm';
    if (fields.startTime) {
      fields.startTime = moment(fields.startTime).format(format);
    }
    if (fields.endTime) {
      fields.endTime = moment(fields.endTime).format(format);
    }

    this.props.dispatch({
      type: 'score/modifyScore',
      payload: fields,
      zubieCode: this.props.zubie.curZubie,
      callback: () => {
        this.setState({
          modalVisible: false,
          curScore: null,
        });
        // this.props.dispatch({
        //   type: 'zubie/queryScore',
        //   payload: {
        //     zubieCode: this.props.zubie.curZubie,
        //   },

        // });
        this.props.dispatch({
          type: 'zubie/queryScoreData',
          payload: {
            zubieCode: this.props.zubie.curZubie,
            phaseCode: this.state.curPhase,
          },
        });
      },
    });
  };

  onSelectZubie = value => {
    this.setState({
      curZubie: value,
    });

    this.props.dispatch({
      type: 'zubie/changeState',
      payload: {
        curZubie: value,
      },
    });

    this.props.dispatch({
      type: 'zubie/queryPhase',
      payload: value,
    });

    this.props.dispatch({
      type: 'zubie/queryZubieByCode',
      payload: value,
    });

    // this.props.dispatch({
    //   type: 'zubie/queryScore',
    //   payload: {
    //     zubieCode: value,
    //   },
    // });
    this.props.dispatch({
      type: 'zubie/queryScoreData',
      payload: {
        zubieCode: value,
      },
    });
  };

  finishPhase = phaseCode => {
    this.props.dispatch({
      type: 'phase/finish',
      payload: phaseCode,
      callback: () => {
        this.props.dispatch({
          type: 'zubie/queryPhase',
          payload: this.props.zubie.curZubie,
        });
        message.success('阶段已完成');
      },
    });
  };

  renderSimpleForm() {
    const {
      zubie: { curZubieObj, zubieList, curZubie },
    } = this.props;

    return (
      <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
        <Col md={8} sm={24}>
          <FormItem label="请选择组别">
            <Select
              placeholder="未选择"
              style={{ width: '100%' }}
              onChange={this.onSelectZubie}
              value={curZubie}
            >
              {zubieList.map(element => {
                if (element.enabled)
                  return (
                    <Option key={'OP' + element.code} value={element.code}>
                      {convertProjectCode(element.projectCode) + ' - ' + element.zubieName}
                    </Option>
                  );
              })}
            </Select>
          </FormItem>
        </Col>
        {!curZubie && (
          <Col md={4} sm={16}>
            <FormItem>
              <Alert
                style={{ flex: 1 }}
                message="请选择一个组别"
                type="error"
                icon={<Icon type="left" />}
                showIcon={true}
              />
            </FormItem>
          </Col>
        )}
        {/* {curZubieObj &&
          curZubieObj.status === 'FI' && (
            <Col md={8} sm={24}>
              <Button type="primary" style={{ marginLeft: 8 }}>
                下载成绩册
              </Button>
            </Col>
          )} */}
      </Row>
    );
  }

  expandedRowRender = (record, index) => {
    const team1 =
      record.athlethList1 &&
      record.athlethList1
        .map(value => {
          return value.userName;
        })
        .join(',');
    const team2 =
      record.athlethList2 &&
      record.athlethList2
        .map(value => {
          return value.userName;
        })
        .join(',');
    const columns = [
      {
        title: '场序',
        dataIndex: 'seq',
        key: 'match_score_seq',
        render: value => <span>第{value}场</span>,
      },
      { title: team1, dataIndex: 'score1', key: 'score_score1' },
      { title: team2, dataIndex: 'score2', key: 'score_score2' },
      { title: '开始时间', dataIndex: 'startTime', key: 'score_start_time' },
      { title: '结束时间', dataIndex: 'endTime', key: 'score_end_time' },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'score_status',
        render: value =>
          value === 'NEW'
            ? '未开始'
            : value === 'FINISH'
              ? '已完成'
              : value === 'ONGOING'
                ? '比赛中'
                : '选手退赛',
      },
      {
        title: '操作',
        width: 170,
        key: 'operation',
        render: (value, item) =>
          !record.isVirtual && (
            <Button
              size="small"
              onClick={() => {
                item.team1 = team1;
                item.team2 = team2;
                this.modifyScore(item);
              }}
            >
              编辑
            </Button>
          ),
      },
    ];
    return (
      <Table
        size="small"
        bordered
        columns={columns}
        dataSource={record.scoreList}
        pagination={false}
      />
    );
  };

  renderScoreImport = () => {
    const {
      zubie: { curZubieObj },
    } = this.props;
    return (
      <div>
        <Button
          disabled={
            (curZubieObj && curZubieObj.status === 'NEW') ||
            (curZubieObj && curZubieObj.status === 'BC')
          }
          style={{ marginRight: 10 }}
          onClick={this.downloadScore}
        >
          下载成绩册
        </Button>
        <Upload
          action={`/bgms/gameScore/upload/${this.props.zubie.curZubie}`}
          name="file"
          disabled={this.props.zubie.curZubie ? false : true}
          showUploadList={false}
          onChange={this.importScore}
        >
          <Button
            disabled={
              curZubieObj &&
              (curZubieObj.status === 'NEW' || (curZubieObj && curZubieObj.status === 'BC'))
            }
            type="primary"
            style={{ marginLeft: 8 }}
          >
            导入成绩册
          </Button>
        </Upload>
      </div>
    );
  };

  downloadScore = () => {
    if (this.props.zubie.curZubie)
      window.open('/bgms/gameScore/download/' + this.props.zubie.curZubie, 'GET');
    else message.warn('请先选择组别');
  };

  importScore = value => {
    if (value.file.status === 'error') {
      notification.error({
        message: '错误',
        description: value.file.response ? value.file.response.msg : '上传的文件有问题',
      });
    } else if (value.file.status === 'done') {
      message.success('成绩册导入成功');
      // this.props.dispatch({
      //   type: 'zubie/queryScore',
      //   payload: {
      //     zubieCode: this.props.zubie.curZubie,
      //   },
      // });
      this.props.dispatch({
        type: 'zubie/queryScoreData',
        payload: {
          zubieCode: this.props.zubie.curZubie,
          phaseCode: this.state.curTabPhase,
        },
      });
    }
  };

  tabChange = value => {
    if (value.indexOf('nodata-') !== -1) {
      return;
    }

    const titleArray = value.split('_');
    this.setState({
      curTabPhase: titleArray[0],
    });
    this.props.dispatch({
      type: 'zubie/changeState',
      payload: {
        zhixuScoreList: {},
      },
    });
    this.props.dispatch({
      type: 'zubie/queryScoreData',
      payload: {
        zubieCode: this.props.zubie.curZubie,
        phaseCode: titleArray[0],
      },
    });
  };

  renderOutTree = (phaseCode, saishiList) => {
    saishiList.sort((obj1, obj2) => {
      if (obj1.round < obj2.round) {
        return -1;
      } else if (obj1.round < obj2.round) {
        return 1;
      } else {
        if (obj1.id < obj2.id) {
          return -1;
        } else if (obj1.id > obj2.id) {
          return 1;
        } else {
          return 0;
        }
      }
    });
    const startRound = saishiList[0] ? saishiList[0].round : 1;
    const matchList = [];
    saishiList.map(element => {
      if (phaseCode === element.phaseCode && element.round === startRound) {
        matchList.push(element);
      }
    });
    return (
      <div
        style={{ height: matchList.length * 100 }}
        id={'scoreTree' + phaseCode}
        ref="container"
      />
    );
  };

  handleScoreChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;

    const params = tableChangePagination(pagination, filtersArg, sorter);
    this.setState({ scorePagination: JSON.parse(JSON.stringify(params)) });
    //params.phaseCode = this.state.curTabPhase
    params.zubieCode = this.props.zubie.curZubie;

    this.props.dispatch({
      type: 'zubie/queryScore',
      payload: params,
    });
  };

  handleTreeQuery = curPage => {
    this.props.dispatch({
      type: 'zubie/queryScoreData',
      payload: {
        zubieCode: this.props.zubie.curZubie,
        phaseCode: this.state.curPhase,
        curPage,
      },
    });
  };

  hadlerScoreInput = element => {
    this.setState({
      modifyMatch: element,
    });
    console.log(element);
    this.handleMatchScoreModalVisible(true);
  };

  handleMatchScoreModalVisible = flag => {
    this.setState({
      matchScoreModalVisible: !!flag,
    });
  };

  handleMatchSCoreModify = fields => {
    const format = 'HH:mm';
    if (fields.startTime) {
      fields.startTime = moment(fields.startTime).format(format);
    }
    if (fields.endTime) {
      fields.endTime = moment(fields.endTime).format(format);
    }

    this.props.dispatch({
      type: 'score/modifyScore',
      payload: fields,
      zubieCode: this.props.zubie.curZubie,
      callback: () => {
        // this.props.dispatch({
        //   type: 'zubie/queryScore',
        //   payload: {
        //     zubieCode: this.props.zubie.curZubie,
        //   },
        // });
        message.success('成绩修改完成');
        this.state.modifyMatch &&
          this.state.modifyMatch.scoreList &&
          this.state.modifyMatch.scoreList.forEach(element => {
            if (element.id === fields.id) {
              element.score1 = fields.score1;
              element.score2 = fields.score2;
              element.startTime = fields.startTime;
              element.endTime = fields.endTime;
            }
          });
        this.setState({
          modifyMatch: this.state.modifyMatch,
        });
        this.props.dispatch({
          type: 'zubie/queryScoreData',
          payload: {
            zubieCode: this.props.zubie.curZubie,
            phaseCode: this.state.curPhase,
          },
        });
      },
    });
  };

  render() {
    const {
      zubie: { curZubieObj, phaseList, scoreList, zhixuScoreList },
      loading,
    } = this.props;
    const { modalVisible, matchScoreModalVisible } = this.state;

    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
    };

    const zhixuColumns = [
      {
        title: '代号',
        dataIndex: 'bisaiId',
      },
      {
        title: '项目',
        dataIndex: 'project',
      },
      {
        title: '组别',
        dataIndex: 'fenzuName',
      },
      {
        title: '轮次',
        dataIndex: 'roundName',
      },
      {
        title: '抽签号',
        dataIndex: 'gamePosName1',
      },
      {
        title: '所属团队',
        dataIndex: 'team1',
      },
      {
        title: '运动员',
        dataIndex: 'athlethList1',
        render: value => (
          <span>
            {value &&
              value
                .map(value => {
                  return value.userName;
                })
                .join(',')}
          </span>
        ),
      },
      {
        title: '对阵',
        render: () => <span>VS</span>,
      },
      {
        title: '抽签号',
        dataIndex: 'gamePosName2',
      },
      {
        title: '所属团队',
        dataIndex: 'team2',
      },
      {
        title: '运动员',
        dataIndex: 'athlethList2',
        render: value => (
          <span>
            {value &&
              value
                .map(value => {
                  return value.userName;
                })
                .join(',')}
          </span>
        ),
      },
      {
        title: '场地',
        dataIndex: 'placeName',
      },
      {
        title: '场序',
        dataIndex: 'changxu',
      },
      {
        title: '日期',
        dataIndex: 'matchDate',
        render: value => <span>{value && value.substring(0, 10)}</span>,
      },
      {
        title: '时段',
        dataIndex: 'timePhase',
        render: value => {
          switch (value) {
            case 'A':
              return <span>上午</span>;
            case 'B':
              return <span>下午</span>;
            case 'C':
              return <span>晚上</span>;
          }
        },
      },
      {
        title: '时间',
        dataIndex: 'placeTime',
      },
    ];

    const placeMethod = {
      handleAdd: this.handleMatchSCoreModify,
      handleModalVisible: this.handleMatchScoreModalVisible,
    };

    return (
      <Fragment>
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
            <Tabs
              defaultActiveKey="1"
              onChange={this.tabChange}
              tabBarExtraContent={this.props.zubie.curZubie && this.renderScoreImport()}
            >
              {phaseList.map(element => (
                <TabPane
                  tab={!element.isFinished ? element.name : element.name + '(已完成)'}
                  key={element.code + '_' + element.lastPhase + '_' + element.gameMethod}
                >
                  {curZubieObj &&
                    curZubieObj.status === 'AC' &&
                    !element.isFinished && (
                      <div style={{ textAlign: 'right' }}>
                        <Button
                          type="primary"
                          style={{ marginBottom: 20 }}
                          onClick={() => this.finishPhase(element.code)}
                        >
                          阶段完成
                        </Button>
                      </div>
                    )}
                  {zhixuScoreList &&
                    zhixuScoreList.gameMethod &&
                    (zhixuScoreList.gameMethod === 'CYCLE' || zhixuScoreList.gameMethod === 'FENZU'
                      ? generateScoreTable(
                          null,
                          zhixuScoreList.list,
                          this.hadlerScoreInput,
                          element.isFinished
                        )
                      : generateTreeTable(
                          null,
                          zhixuScoreList,
                          this.handleTreeQuery,
                          this.hadlerScoreInput,
                          element.isFinished
                        ))}
                </TabPane>
              ))}
            </Tabs>
          </div>
        </Card>
        <CreateForm {...parentMethods} modalVisible={modalVisible} curScore={this.state.curScore} />
      </Fragment>
    );
  }
}
